#include"String.h"
#include<iomanip>
#include<cstdlib>
#pragma warning(disable:4996)
ostream &operator<<(ostream &output, const String &str) {
	output << str.m_pStr;
	return output;
}
istream &operator>>(istream &input, String &str) {
	char temp[100];
	input >> setw(100) >> temp;
	str = temp;
	return input;
}

String::String(const char *str)
	:m_iLength((str != NULL) ? strlen(str) : 0){
	cout << "Conversion (and default) constructor " << str << endl;
	setString(str);
}

String::String(const String &str)
		:m_iLength(str.m_iLength){
	cout << "Copy constructor: " << str.m_pStr << endl;
	setString(str.m_pStr);
}
String::~String(){
	cout << "Destructor: " << m_pStr << endl;
	delete[] m_pStr;
}

const String &String::operator=(const String &right){
	cout << "operator= called" << endl;

	if (&right != this) {
		delete[] this->m_pStr;
		this->m_iLength = right.m_iLength;
		setString(right.m_pStr);
	}
	else {
		cout << "Attempted assignment of a String to itself" << endl;
	}
	return *this;
}

const String &String::operator+=(const String &right){
	size_t newLength = m_iLength + right.m_iLength;
	char *tempPtr = new char[newLength + 1];

	strcpy(tempPtr, m_pStr);
	strcpy(tempPtr + m_iLength, right.m_pStr);

	delete[] m_pStr;
	m_pStr = tempPtr;
	m_iLength = newLength;
	return *this;
}

bool String::operator!() const{
	return m_iLength == 0;
}

bool String::operator==(const String &right) const{
	return strcmp(m_pStr, right.m_pStr) == 0;
}

bool String::operator<(const String &right) const{
	return strcmp(m_pStr, right.m_pStr) < 0;
}

char &String::operator[](int index){
	if (index < 0 || index >= m_iLength) {
		cerr << "Error: index " << index << "out of range" << endl;
		exit(EXIT_FAILURE);
	}
	return m_pStr[index];
}

char String::operator[](int index) const{
	if (index < 0 || index >= m_iLength) {
		cerr << "Error: index " << index << "out of range" << endl;
		exit(EXIT_FAILURE);
	}
	return m_pStr[index];

}
String String::operator()(int index, int subLength) {
	if (index < 0 || index >= m_iLength || subLength < 0) {
		return "";
	}
	int len;
	if ((subLength == 0) || (index + subLength > m_iLength)) {
		len = m_iLength - index;
	}
	else {
		len = subLength;
	}
	char *tempPtr = new char[len + 1];
	strncpy(tempPtr, &m_pStr[index], len);
	tempPtr[len] = '\0';
	String tempString(tempPtr);
	delete[] tempPtr;
	return tempString;
}
int String::getLength() const {
	return m_iLength;
}

void String::setString(const char *string2) {
	
	if (string2 != 0) {
		m_pStr = new char[strlen(string2) + 1];
		strcpy(m_pStr, string2);
	}
	else {
		m_pStr = new char;
		m_pStr[0] = '\0';
	}
}








